import db from "@/db/db";
import { NextResponse } from "next/server";
let msg = "Post not found";
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { posts } = db.data;
  const post = posts.find(post => post.id === id);
  if (post) {
    msg = "Post found";
    return NextResponse.json({
      code:'0',
      msg,
      data: post
    });
  } else {
    msg = "Post not found";
    return NextResponse.json({ code:'1', msg });
  }
}

export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  let deleted = false;
  await db.update(({ posts }) => {
    const index = posts.findIndex(post => post.id === id);
    if (index !== -1) {
      posts.splice(index, 1);
      deleted = true;
    }
  });
  if (deleted) {
    msg = "Post deleted";
    return NextResponse.json({ code:'0', msg });
  } else {
    msg = "Post not found";
    return NextResponse.json({ code:'1', msg });
  }
}

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const body = await request.json();
  let updated = false;
  
  await db.update(({ posts }) => {
    const index = posts.findIndex(post => post.id === id);
    if (index !== -1) {
      const temp = posts[index]
      const newVal = { ...temp, ...body };
      if(JSON.stringify(temp) === JSON.stringify(newVal)){
        updated = false;
        msg = "No changes made";
      }else{
        posts[index] = newVal;
        updated = true;
        msg = "Post updated";
      }
    }
  });
  if (updated) {
    return NextResponse.json({ 
      code:'0',
      msg,
      data: body
    });
  } else {
    return NextResponse.json({ 
      code:'1',
      msg,
    });
  }
}